package shuzi.activity;

import java.util.ArrayList;
import java.util.List;

import shuzi.adapter.OrderAdapter;
import shuzi.data.Database;
import shuzi.model.BrandPhone;
import shuzi.util.Dialog;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.shuzi.offer.R;

public class OrderActivity extends Activity implements OnClickListener {

	/** 刷新界面的handler */
	private Handler handler = null;
	/** 全部数据 */
	private List<BrandPhone> listOrder = null;
	/** 滚动 */
	private ProgressBar progressBar = null;
	/** 列表 */
	private ListView listView = null;
	/** 适配器 */
	private OrderAdapter adapter = null;
	/** 打电话 */
	private ImageView phone = null;
	/** 发短信 */
	private ImageView sms = null;
	/** 数量 */
	private TextView count = null;
	/** 总价 */
	private TextView allPrices = null;
	/** 总数量   */
	private int nowNumber = 0;
	/** 总价钱   */
	private int zongjia = 0;
	
	/**发送与接收的广播**/  
    String SENT_SMS_ACTION = "SENT_SMS_ACTION";  
    String DELIVERED_SMS_ACTION = "DELIVERED_SMS_ACTION";
    
    @Override
    protected void onRestart() {
    	super.onRestart();
    	 Database.yiXuanMap.clear();
         Database.yiXuanList.clear();
         Intent in = new Intent(OrderActivity.this, MainActivity.class);
         startActivity(in);
         finish();
    }
    

      
    private BroadcastReceiver sendMessage = new BroadcastReceiver() {  
  
    @Override  
    public void onReceive(Context context, Intent intent) {  
        //判断短信是否发送成功  
        switch (getResultCode()) {  
        case Activity.RESULT_OK:  
        Toast.makeText(context, "短信发送成功", Toast.LENGTH_SHORT).show(); 
        Database.yiXuanMap.clear();
        Database.yiXuanList.clear();
        Intent in = new Intent(context, MainActivity.class);
        startActivity(in);
        finish();
        break;  
        default:  
        Toast.makeText(context, "发送失败", Toast.LENGTH_LONG).show();  
        break;  
        }  
    }  
    };  
      
     
    private BroadcastReceiver receiver = new BroadcastReceiver() {  
  
    @Override  
    public void onReceive(Context context, Intent intent) {  
        //表示对方成功收到短信  
        Toast.makeText(context, "对方接收成功",Toast.LENGTH_LONG).show();  
    }  
    };  

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.order_info);

		initHandler();
		initLayout();
		initDada();
		
		 // 注册广播 发送消息  
	    registerReceiver(sendMessage, new IntentFilter(SENT_SMS_ACTION));  
	    registerReceiver(receiver, new IntentFilter(DELIVERED_SMS_ACTION));  
	  
	    
	    
	}
	
	@Override
	protected void onDestroy() {
		unregisterReceiver(sendMessage);
		unregisterReceiver(receiver);
		super.onDestroy();
	}

	/**
	 * 初始化handler
	 */
	@SuppressLint("HandlerLeak")
	private void initHandler() {
		handler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				progressBar.setVisibility(View.GONE);
				switch (msg.what) {
				case Database.HANDLER_REFRESH_LISTVIEW:
					adapter = new OrderAdapter(OrderActivity.this, listOrder) {
						@Override
						public void setZongjia() {
							super.setZongjia();
							setNowZongjia();
						}

					};
					listView.setAdapter(adapter);
					registerForContextMenu(listView);
					setNowZongjia();
					break;
				case Database.HANDLER_REFRESH_ERROR:

					break;
				case Database.HANDLER_REFRESH_NODATA:
					progressBar.setVisibility(View.GONE);
					Toast.makeText(OrderActivity.this, "暂无数据",
							Toast.LENGTH_LONG).show();
					break;

				default:
					break;
				}
			}
		};

	}
	
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		//super.onCreateContextMenu(menu, v, menuInfo);
		 menu.setHeaderTitle("文件操作");
		    // add context menu item
		    menu.add(0, 1, Menu.NONE, "发送");
		    menu.add(0, 2, Menu.NONE, "标记为重要");
		    menu.add(0, 3, Menu.NONE, "重命名");
		    menu.add(0, 4, Menu.NONE, "删除");
		
	}
	
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		return super.onContextItemSelected(item);
		// 得到当前被选中的item信息
	    
	}
	
	/**
	 * 设置当前的总价
	 */
	private void setNowZongjia() {
		nowNumber = 0;
		zongjia = 0;
		for(BrandPhone phone:listOrder){
			nowNumber = nowNumber+ phone.getNumber();
			zongjia = zongjia+ phone.getNumber()*Integer.parseInt(phone.getPrice());
		}
		count.setText(nowNumber+"");
		allPrices.setText("￥"+zongjia);
	}

	/**
	 * 初始化布局
	 */
	private void initLayout() {
		listView = (ListView) findViewById(R.id.orderListview);
		progressBar = (ProgressBar) findViewById(R.id.progressBar);
		listView.setCacheColorHint(0);
		phone = (ImageView) findViewById(R.id.phone);
		sms = (ImageView) findViewById(R.id.sms);
		count = (TextView) findViewById(R.id.number);
		allPrices = (TextView) findViewById(R.id.allPrice);

		phone.setOnClickListener(this);
		sms.setOnClickListener(this);

	}

	/**
	 * 初始化数据
	 */
	private void initDada() {
		listOrder = new ArrayList<BrandPhone>();
		for (Object m : Database.yiXuanMap.keySet()) {
			listOrder.add(Database.yiXuanMap.get(m));
		}

		if (listOrder.size() == 0) {
			handler.sendEmptyMessage(Database.HANDLER_REFRESH_ERROR);
		} else {
			handler.sendEmptyMessage(Database.HANDLER_REFRESH_LISTVIEW);
		}

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.phone:
			Dialog.callDialog(OrderActivity.this);
			break;

		case R.id.sms:
			Intent intent = new Intent();

			//系统默认的action，用来打开默认的短信界面
			intent.setAction(Intent.ACTION_SENDTO);

			//需要发短息的号码
			intent.setData(Uri.parse("smsto:"+Database.dealer.getDealerContactNumber()));
			int price = 0;
			StringBuilder builder = new StringBuilder();
			builder.append("你下的订单为:");
			for(BrandPhone order: listOrder){
			
				builder.append(order.getName()+",数量为"+order.getNumber()+"台,"+"颜色为");
				if(order.getChoiceColor()==Database.BLACK){
					builder.append("黑色,");
					price = Integer.parseInt(order.getBlackPrice())*order.getNumber()+price;
				}else if(order.getChoiceColor()==Database.WHITE){
					builder.append("白色,");
					price = Integer.parseInt(order.getWihtePrice())*order.getNumber()+price;
				}else if(order.getChoiceColor()==Database.OTHER){
					builder.append("其他颜色,");
					price = Integer.parseInt(order.getOtherPrice())*order.getNumber()+price;
				}
				builder.append("价格为"+Integer.parseInt(order.getPrice())*order.getNumber()+";"+"\n");
			}
			builder.append("总价为"+price+"\n");
			intent.putExtra("sms_body", builder.toString());
			startActivity(intent);
		//	Dialog.sentSMSDialog(OrderActivity.this);
			break;
		}

	}
}
